package com.nstskj.study.netty.tcp.netty.protocol.endpoint.base;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.nstskj.study.netty.tcp.netty.protocol.endpoint.data.EndpointData;
import lombok.Data;

import java.io.Serializable;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @author ZhouChuGang
 * @version 1.0
 * @project nstskj-study-netty-tcp-spring
 * @date 2021/5/3 16:54
 * @Description 抽象的协议端点
 */
@Data
public abstract class AbstractEndpoint implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 端点地址
     */
    private final short address;

    /**
     * 是否为输出端点
     */
    private final boolean isOut;

    /**
     * 端点数据缓存长度
     */
    private final int buffLen;

    /**
     * 端点数据队列
     */
    @JsonIgnore
    private final BlockingQueue<EndpointData> queue;

    /**
     * 构造函数
     *
     * @param address 端点地址
     * @param isOut   是否为输出端点
     * @param buffLen 端点的缓存长度
     */
    public AbstractEndpoint(short address, boolean isOut, int buffLen) {
        this.address = address;
        this.isOut = isOut;
        this.buffLen = buffLen;
        this.queue = new LinkedBlockingDeque<>(100);
    }

    /**
     * 添加端点数据
     *
     * @param endpointData
     * @return
     */
    public boolean addEndpointData(EndpointData endpointData) {
        //如果容器没满，则插入成功
        return this.getQueue().offer(endpointData);
    }

}
